package com.cm.projectx.util;

import com.cm.projectx.common.entity.UserContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

/**
 * 用于调用外部接口工具类
 */
@Component
public class HttpUtils {
    @Value("${spring.low.code.host}")
    private String lowCodeHost;

    private final RestTemplate restTemplate;

    public HttpUtils(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 发送GET请求
     * @param url 请求地址
     * @param params 请求参数
     * @param responseType 响应类型
     * @return 响应结果
     */
    public <T> T get(String url, Map<String, Object> params, Class<T> responseType) {
        // 构建请求头
        HttpHeaders headers = createHeadersWithToken();
        HttpEntity<?> entity = new HttpEntity<>(headers);

        // 构建URL参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(lowCodeHost + url);
        if (params != null) {
            params.forEach(builder::queryParam);
        }

        // 发送请求
        ResponseEntity<T> response = restTemplate.exchange(
                builder.build().toUri(),
                HttpMethod.GET,
                entity,
                responseType
        );

        return response.getBody();
    }

    /**
     * 重写：发送GET请求(针对定时任务重写此方法，根据传入的token请求，不然从设置的上下问中拿不到token)
     * @param url 请求地址
     * @param params 请求参数
     * @param responseType 响应类型
     * @return 响应结果
     */
    public <T> T get(String url,String token ,Map<String, Object> params, Class<T> responseType) {
        // 构建请求头
        HttpHeaders headers = createHeadersWithToken(token);
        HttpEntity<?> entity = new HttpEntity<>(headers);

        // 构建URL参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(lowCodeHost + url);
        if (params != null) {
            params.forEach(builder::queryParam);
        }

        // 发送请求
        ResponseEntity<T> response = restTemplate.exchange(
                builder.build().toUri(),
                HttpMethod.GET,
                entity,
                responseType
        );

        return response.getBody();
    }
    /**
     * 重写：发送POST请求（JSON格式）(可传入token的用于定时任务)
     * @param url 请求地址
     * @param body 请求体
     * @param responseType 响应类型
     * @return 响应结果
     */
    public <T> T postJson(String url,String token ,Object body, Class<T> responseType) {
        // 构建请求头
        HttpHeaders headers = createHeadersWithToken(token);
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(lowCodeHost + url);
        // 发送请求
        return restTemplate.postForObject(builder.build().toUri(), entity, responseType);
    }

    public <T> T postJson(String url,Object body, Class<T> responseType) {
        // 构建请求头
        HttpHeaders headers = createHeadersWithToken();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(lowCodeHost + url);
        // 发送请求
        return restTemplate.postForObject(builder.build().toUri(), entity, responseType);
    }

    /**
     * 发送POST请求（表单格式）
     * @param url 请求地址
     * @param formData 表单数据
     * @param responseType 响应类型
     * @return 响应结果
     */
    public <T> T postForm(String url, Map<String, Object> formData, Class<T> responseType) {

        // 构建请求头
        HttpHeaders headers = createHeadersWithToken();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(formData, headers);

        // 发送请求
        return restTemplate.postForObject(url, entity, responseType);
    }

    /**
     * 发送PUT请求
     * @param url 请求地址
     * @param body 请求体
     * @param responseType 响应类型
     * @return 响应结果
     */
    public <T> T put(String url,  Object body, Class<T> responseType) {
        // 构建请求头
        HttpHeaders headers = createHeadersWithToken();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Object> entity = new HttpEntity<>(body, headers);

        // 发送请求
        ResponseEntity<T> response = restTemplate.exchange(
                url,
                HttpMethod.PUT,
                entity,
                responseType
        );

        return response.getBody();
    }

    /**
     * 发送DELETE请求
     * @param url 请求地址
     * @param params 请求参数
     * @param responseType 响应类型
     * @return 响应结果
     */
    public <T> T delete(String url,  Map<String, Object> params, Class<T> responseType) {
        // 构建请求头
        HttpHeaders headers = createHeadersWithToken();
        HttpEntity<?> entity = new HttpEntity<>(headers);

        // 构建URL参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (params != null) {
            params.forEach(builder::queryParam);
        }

        // 发送请求
        ResponseEntity<T> response = restTemplate.exchange(
                builder.build().toUri(),
                HttpMethod.DELETE,
                entity,
                responseType
        );

        return response.getBody();
    }

    /**
     * 创建带有token的请求头
     * @return 包含token的HttpHeaders对象
     */
    private HttpHeaders createHeadersWithToken() {
        //String token = UserContext.getCurrentUser().getToken();
        String token = "1NiIsImV4cCI6MTY0MDg0MjczOCwidXNlcm5hbWUiOiIxMjMifQ.7wGTMbod1HJstqwLbsCS7G-Nd4TIzVTVsl220OjwVUs";
        HttpHeaders headers = new HttpHeaders();
        if (token != null && !token.trim().isEmpty()) {
            headers.set("Token",token);
        }
        return headers;
    }

    /**
     * 重写：创建带有token的请求头(从写带参数的token用于定时任务传入token)
     * @return 包含token的HttpHeaders对象
     */
    private HttpHeaders createHeadersWithToken(String token) {
        HttpHeaders headers = new HttpHeaders();
//        if (token != null && !token.trim().isEmpty()) {
//            headers.set("Token",token);
//        }
        String token1 = "1NiIsImV4cCI6MTY0MDg0MjczOCwidXNlcm5hbWUiOiIxMjMifQ.7wGTMbod1HJstqwLbsCS7G-Nd4TIzVTVsl220OjwVUs";
        headers.set("Token",token1);
        return headers;
    }
}
